from socket import *
from typing import Dict, Optional, Tuple


class UDPSender:
    def __init__(self, port: int) -> None:
        self._th = None
        self.port = port
        # 缓存UDP套接字
        self.socket: Optional[socket] = None

    def send(self, target_ip: str, message: bytes) -> None:
        if not self.socket:
            self.socket = socket(AF_INET, SOCK_DGRAM)
        self.socket.sendto(message, (target_ip, self.port))

    def broadcast(self, message: bytes) -> None:
        """
        发送一条广播消息
        """
        address = ("255.255.255.255", self.port)
        s = socket(AF_INET, SOCK_DGRAM)
        s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        s.sendto(message, address)
        s.close()

    def close(self) -> None:
        if self.socket is not None:
            self.socket.close()
